package com.baihui.taobao.transition;

import java.sql.Connection;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.baihui.taobao.authorize.TaoBaoSessionInfo;
import com.baihui.taobao.db.CommonDAO;
import com.baihui.taobao.db.DBConnectionMgr;
import com.baihui.taobao.db.ShippingDAO;
import com.baihui.taobao.util.Util;
import com.baihui.taobao.vo.BShipping;
import com.taobao.api.ApiException;
import com.taobao.api.TaobaoObject;
import com.taobao.api.domain.Shipping;
import com.taobao.api.request.LogisticsOrdersGetRequest;
import com.taobao.api.response.LogisticsOrdersGetResponse;

/**
 * Created by Kevin. User: HSZM1106-0312 Date: 12-1-27 Time: 下午5:13
 */
public class ShippingCase extends Cases implements IViewProgressSupport {
	public ShippingCase(TaoBaoSessionInfo info) {
		super(info);
	}

	public List<Shipping> getShippingInfo(Date startDate, Date endDate)
			throws Exception {
		LogisticsOrdersGetRequest req = new LogisticsOrdersGetRequest();
		req.setFields(parseFields(Shipping.class));
		long page = 1;
		req.setPageNo(page);
		req.setStartCreated(startDate);
		req.setEndCreated(endDate);
		try {
			LogisticsOrdersGetResponse response = getTaoBaoClient().execute(
					req, getSessionInfo().getTopSession());
			if (response.getErrorCode() != null) {
				throw new Exception();
			}
			List<Shipping> shippingList = response.getShippings();
			if (shippingList == null || shippingList.size() <= 0)
				return null;
			while (response != null
					&& response.getTotalResults() > shippingList.size()) {
				// 存在第二页
				Util.stopOneMinute();
				page++;
				response = getNextPage(req, page);
				if (response.getErrorCode() == null) {
					shippingList.addAll(response.getShippings());
				} else {
					response = getNextPage(req, page);
					shippingList.addAll(response.getShippings());
				}
			}
			if (shippingList == null) {
				throw new Exception(response.getBody());
			}
			return shippingList;
		} catch (Exception e) {
			throw e;
		}
	}

	private SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");

	/**
	 * 1. 根据时间导入，和订单导入算法一致 2. 更新importOrderStatus表 3. 每次导入的数据不超过MAX_COUNT.
	 * 
	 * @param visitor_id
	 * @param lotInfo
	 * @throws Exception
	 */
	public void importShippingFromTaobao(long visitor_id, Date start, Date end)
			throws Exception {
		if (start == null || end == null) {
			end = new Date();
			start = addMonths(end, -3);
		}

		markImportProgress(60);
		Connection cn = null;
		try {
			List<Shipping> shippingList = getShippingInfo(start, end);
			// 取出本用户的所有物流信息
			List<String> shipList = getShippingByUser();
			markImportProgress(62);
			if (shippingList != null && shippingList.size() > 0) {
				List<TaobaoObject> allShipping = new ArrayList<TaobaoObject>();
				for (Shipping shipping : shippingList) {
					if (shipList != null
							&& shipList.contains(String.valueOf(shipping.getOrderCode()))) {
						continue;
					}
					BShipping tmp = new BShipping();
					Util.copy(tmp, shipping);
					tmp.setUserId(visitor_id);
					allShipping.add(tmp);
				}

				cn = DBConnectionMgr.getConnection();
				// log("更新物流信息表！");
				ShippingDAO shippingDAO = new ShippingDAO();
				shippingDAO.insert(allShipping, cn);
				allShipping.clear();
				markImportProgress(65);
			}
			markImportProgress(68);
		} catch (Exception e) {
			// if (cn != null) cn.rollback();
			throw e;
		} finally {
			if (cn != null)
				cn.close();
		}
	}

	/**
	 * 得到最大的结束日期
	 * 
	 * @param startDate
	 * @param endDate
	 * @return
	 * @throws Exception
	 */
	public Timestamp getMaxEndTime(Timestamp startDate, Timestamp endDate)
			throws Exception {
		LogisticsOrdersGetRequest req = new LogisticsOrdersGetRequest();
		req.setFields("tid");
		long page = 1;
		req.setPageNo(page);
		req.setStartCreated(startDate);
		req.setEndCreated(endDate);
		try {
			LogisticsOrdersGetResponse response = getTaoBaoClient().execute(
					req, getSessionInfo().getTopSession());
			if (response.getTotalResults() > getSessionInfo().getTbMaxCount()) {
				long times = response.getTotalResults()
						/ getSessionInfo().getTbMaxCount();
				long period = endDate.getTime() - startDate.getTime();
				if (times >= 1) {
					endDate = new Timestamp(startDate.getTime() + period
							/ times);
				}
			}
			return endDate;
		} catch (ApiException e) {
			throw new Exception(e);
		}
	}

	private LogisticsOrdersGetResponse getNextPage(
			LogisticsOrdersGetRequest req, long page) throws Exception {
		req.setPageNo(page);
		try {
			return getTaoBaoClient().execute(req,
					getSessionInfo().getTopSession());
		} catch (ApiException e) {
			throw new Exception(e);
		}
	}

	public void markImportProgress(int progress) {
		// System.out.println("当前进度：" + progress + "%");
		getSessionInfo().setOrderImportProgress(progress);
	}

	public int viewImportProgress() {
		return getSessionInfo().getOrderImportProgress();
	}

	/**
	 * 本用户对应的物流信息
	 * 
	 * @return
	 */
	public List<String> getShippingByUser() throws Exception {
		CommonDAO commonDAO = new CommonDAO();
		List<String> shippingMap = commonDAO.findListString(
				"select orderCode from tbshipping where userId = ? ",
				new Object[] { getSessionInfo().getVisitor_id() });
		return shippingMap;
	}

}
